package com.dykj.fireFighting.web.buildmanger;

import cn.hutool.core.collection.CollectionUtil;
import com.dykj.fireFighting.api.base.file.entity.DataFiles;
import com.dykj.fireFighting.api.base.file.service.DataFilesService;
import com.dykj.fireFighting.api.socialUnit.buildmanger.dto.BuildingDto;
import com.dykj.fireFighting.api.socialUnit.buildmanger.entity.Building;
import com.dykj.fireFighting.api.socialUnit.buildmanger.entity.Floor;
import com.dykj.fireFighting.api.socialUnit.buildmanger.entity.Partitions;
import com.dykj.fireFighting.api.socialUnit.buildmanger.service.IBuildingService;
import com.dykj.fireFighting.api.socialUnit.buildmanger.service.IFloorService;
import com.dykj.fireFighting.api.socialUnit.buildmanger.service.IPartitionsService;
import com.dykj.fireFighting.api.socialUnit.buildmanger.vo.BuildingVo;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.exception.BaseException;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.common.core.vo.SelectTreeVo;
import com.dykj.fireFighting.common.core.vo.TreeVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 建筑管理-楼栋管理接口
 *
 * @Author aixiaolan
 * @Date 2021-06-22 16:04:02
 */
@Slf4j
@Api(value = "建筑管理-楼栋管理接口", tags = {"建筑管理-楼栋管理接口"})
@RestController
@RequestMapping("buildmanger/building")
public class BuildingController {

    @DubboReference
    private IBuildingService buildingService;
    @DubboReference
    private DataFilesService iDataFilesService;
    @DubboReference
    private IFloorService floorService;
    @DubboReference
    private IPartitionsService partitionsService;


    /**
     * 获取单位id
     *
     * @return String
     */
    public String getEnterpriseId() {
        try {
            return Long.toString(ShiroUtil.getUser().getEnterpriseId());
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new BaseException("请登录系统");
        }
    }

    /**
     * 获取用户名称
     *
     * @return String
     */
    public String getName() {
        try {
            return ShiroUtil.getUser().getName();
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new BaseException("请登录系统");
        }
    }


    /**
     * 建筑管理-楼栋管理列表
     *
     * @return
     */
    @AutoLog(value = "建筑管理-楼栋管理-分页列表查询")
    @ApiOperation(value = "建筑管理-楼栋管理分页列表", notes = "建筑管理-楼栋管理分页列表")
    @GetMapping("/list")
//    @RequiresPermissions("buildmanger/building/list")
    public CommonResult<PageVo<Building>> treeGrid(BuildingDto commonDto) {
        commonDto.setUnitId(getEnterpriseId());
        PageVo<Building> page = buildingService.pageList(commonDto);
        log.info("楼栋查询结果：{}", page.toString());
        return CommonResult.success(page);
    }


    /**
     * 建筑管理-楼栋管理列表下拉选择
     *
     * @return
     */
    @AutoLog(value = "建筑管理-楼栋管理-分页列表查询")
    @ApiOperation(value = "建筑管理-楼栋管理分页列表", notes = "建筑管理-楼栋管理分页列表")
    @GetMapping("/list2")
    public CommonResult<List<Building>> getBuildList() {

        List<Building> page = buildingService.getBuildList(getEnterpriseId());
        log.info("楼栋查询结果数据条数：【{}】", page.size());
        return CommonResult.success(page);
    }

    /**
     * 获取建筑管理-楼栋管理信息
     */
    @AutoLog(value = "建筑管理-楼栋管理-获取建筑管理-楼栋管理信息")
    @ApiOperation(value = "获取建筑管理-楼栋管理信息", notes = "获取建筑管理-楼栋管理信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{id}")
//    @RequiresPermissions("buildmanger/building/info")
    public CommonResult<BuildingVo> info(@PathVariable("id") String id) {
        BuildingVo buildingVo = new BuildingVo();

        Building building = buildingService.getById(id);
        BeanUtils.copyProperties(building, buildingVo);
        List<DataFiles> dataFilesList = iDataFilesService.queryReId(id);
        if (CollectionUtil.isNotEmpty(dataFilesList)) {
            buildingVo.setImageUrl(dataFilesList.get(0).getId());
        }
        return CommonResult.success(buildingVo);
    }

    /**
     * 保存建筑管理-楼栋管理信息
     */
    @AutoLog(value = "建筑管理-楼栋管理-保存建筑管理-楼栋管理信息")
    @ApiOperation(value = "保存建筑管理-楼栋管理信息", notes = "保存建筑管理-楼栋管理信息")
    @PostMapping("/save")
//    @RequiresPermissions("buildmanger/building/save")
    public CommonResult save(@Valid @RequestBody BuildingDto buildingDto) {
        try {
            Building building = new Building();
            BeanUtils.copyProperties(buildingDto, building);
            building.setId(UUIDUtils.get32UUID());
            building.setCreateTime(new Date());
            building.setCreateBy(getName());
            building.setUnitId(getEnterpriseId());

            if (StringUtils.isNotBlank(building.getPaths())) {
                String paths = StringEscapeUtils.unescapeHtml(building.getPaths());
                paths = StringEscapeUtils.unescapeHtml(paths);
                building.setPaths(paths);
            }
            buildingService.save(building);
            if (StringUtils.isNotBlank(buildingDto.getImageUrl())) {
                List<String> imageUrlList = new ArrayList<>();
                imageUrlList.add(buildingDto.getImageUrl());
                iDataFilesService.updateFile(imageUrlList, building.getId());
            }
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 修改建筑管理-楼栋管理信息
     */
    @AutoLog(value = "建筑管理-楼栋管理-修改建筑管理-楼栋管理信息")
    @ApiOperation(value = "修改建筑管理-楼栋管理信息", notes = "修改建筑管理-楼栋管理信息")
    @PostMapping("/update")
//    @RequiresPermissions("buildmanger/building/update")
    public CommonResult update(@Valid @RequestBody Building building) {
        try {
            building.setUpdateTime(new Date());
            building.setUpdateBy(getName());
            buildingService.updateById(building);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 删除建筑管理-楼栋管理信息
     */
    @AutoLog(value = "建筑管理-楼栋管理-删除建筑管理-楼栋管理信息")
    @ApiOperation(value = "删除建筑管理-楼栋管理信息", notes = "删除建筑管理-楼栋管理信息")
    @ApiImplicitParam(paramType = "query", name = "ids", value = "ID数组", dataType = "String", required = true, allowMultiple = true)
    @PostMapping("/delete")
//    @RequiresPermissions("buildmanger/building/delete")
    public CommonResult delete(@RequestBody String[] ids) {
        try {
            buildingService.removeByIds(Arrays.asList(ids));
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 部门 -- 楼栋
     *
     * @return
     */
    @AutoLog(value = "部门楼栋")
    @ApiOperation(value = "部门 -- 楼栋", notes = "部门 -- 楼栋")
    @GetMapping("/queryBuildTree")
    public CommonResult<List<TreeVo>> queryBuildTree() {
        LoginUserVo user = ShiroUtil.getUser();
        List<TreeVo> treeVoList = new ArrayList<>();

        TreeVo treeVo = new TreeVo();
        treeVo.setId(user.getEnterpriseId().toString());
        treeVo.setLabel(user.getEnterpriseName());

        List<Building> buildingList = buildingService.getBuildList(getEnterpriseId());

        if (CollectionUtil.isNotEmpty(buildingList)) {
            List<TreeVo> childTreeVoList = Lists.transform(buildingList, (entity) -> {
                TreeVo childTreeVo = new TreeVo();
                childTreeVo.setId(entity.getId());
                childTreeVo.setLabel(entity.getName());
                return childTreeVo;
            });
            treeVo.setChildren(childTreeVoList);
        }
        treeVoList.add(treeVo);
        return CommonResult.success(treeVoList);
    }

    /**
     * 部门 -- 楼栋 --  楼层  -- 分区
     *
     * @return
     */
    @AutoLog(value = "部门--楼栋--楼层--分区")
    @ApiOperation(value = "部门--楼栋--楼层--分区", notes = "部门--楼栋--楼层--分区")
    @GetMapping("/queryBuildFloorPartitionsTree")
    public CommonResult<TreeVo> queryBuildFloorPartitionsTree() {
        LoginUserVo user = ShiroUtil.getUser();
        List<TreeVo> treeVoList = new ArrayList<>();

        TreeVo treeVo = new TreeVo();
        treeVo.setId(user.getEnterpriseId().toString());
        treeVo.setLabel(user.getEnterpriseName());
        treeVo.set_level(0);

        List<TreeVo> buildingList = buildingService.queryBuildFloorPartitionsTree(getEnterpriseId());
        treeVo.setChildren(buildingList);
        return CommonResult.success(treeVo);
    }

    /**
     * 楼栋楼层分区信息查询
     *
     * @param buildId
     * @param floorId
     * @param partitionsId
     * @return
     */
    @AutoLog(value = "楼栋楼层分区信息查询")
    @ApiOperation(value = "楼栋楼层分区信息查询", notes = "楼栋楼层分区信息查询")
    @GetMapping("/queryBuildFloorPartitionsInfo")
    public CommonResult<BuildingVo> queryBuildFloorPartitionsInfo(String buildId, String floorId, String partitionsId) {
        BuildingVo buildingVo = buildingService.queryBuildFloorPartitionsInfo(buildId, floorId, partitionsId);
        List<DataFiles> dataFilesList = iDataFilesService.queryReId(buildId);
        if (CollectionUtil.isNotEmpty(dataFilesList) && dataFilesList.size() > 0) {
            buildingVo.setImageUrl(dataFilesList.get(0).getId());
        }
        return CommonResult.success(buildingVo);
    }

    /**
     * el-tree要求的分区树形数据
     * @return
     */
    @GetMapping("/queryBuildFloorPartitionsTree1")
    public CommonResult<List<SelectTreeVo>> queryBuildFloorPartitionsTree1(){
        try{
        List<Building> buildList = buildingService.getBuildList(getEnterpriseId());
        List<SelectTreeVo> treeNodeList = Lists.newArrayList();
            treeNodeList.add(SelectTreeVo.createParent());
        if (!buildList.isEmpty()){
            for (Building building:buildList) {
                SelectTreeVo selectTreeVo = new SelectTreeVo();
                selectTreeVo.setId(building.getId());
                selectTreeVo.setName(building.getName());
                selectTreeVo.setParentId("0");
                treeNodeList.add(selectTreeVo);
                List<Floor> floorList = floorService.getFloorListByBuildingId(building.getId());
                if(floorList!=null && !floorList.isEmpty()){
                    for (Floor floor: floorList) {
                        SelectTreeVo floorSelectTreeVo = new SelectTreeVo();
                        floorSelectTreeVo.setId(floor.getId());
                        floorSelectTreeVo.setName(floor.getName());
                        floorSelectTreeVo.setParentId(building.getId());
                        treeNodeList.add(floorSelectTreeVo);
                        List<Partitions> partitionsList = partitionsService.getPartitionsListByFloorId(floor.getId());
                        if(partitionsList!=null && !partitionsList.isEmpty()){
                            for (Partitions partitions:partitionsList) {
                                SelectTreeVo partitionsSelectTreeVo = new SelectTreeVo();
                                partitionsSelectTreeVo.setId(partitions.getId());
                                partitionsSelectTreeVo.setName(partitions.getName());
                                partitionsSelectTreeVo.setParentId(floor.getId());
                                treeNodeList.add(partitionsSelectTreeVo);
                            }
                        }
                    }
                }
            }
        }
        return  CommonResult.success(treeNodeList);
        }catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("运行异常，请联系管理员");
        }
    }
}
